﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DropperController : MonoBehaviour 
{

	public GameObject waterRoot;
	public GameObject cutPanle_diguan;
	public GameObject absorbCutpanle;
	RaycastHit hit;

	public void Action()
	{
		if (Physics.Raycast (waterRoot.transform.position, waterRoot.transform.forward, out hit, 10, 1 << 9)) {
			Debug.Log (hit.collider.name);
			if (hit.collider.GetComponent<TestCutWater> () != null) {
				absorbCutpanle = hit.collider.gameObject;
				AbsorbAction ();
				return;
			}
		} else if (Physics.Raycast (waterRoot.transform.position, -waterRoot.transform.forward, out hit, 10, 1 << 10)) {
			if (hit.collider.GetComponent<TestCutWater> () != null && hit.collider.gameObject != cutPanle_diguan) {
				DropAction ();
			}
		} else if (Physics.Raycast (waterRoot.transform.position, -waterRoot.transform.forward, out hit, 50, 1 << 11)) {
			if (Physics.Raycast (waterRoot.transform.position, -waterRoot.transform.forward, out hit, 50, 1 << 12))
				return;
			DropAction ();
		}
	}

	public void DropAction()
	{
		if (cutPanle_diguan.GetComponent<TestCutWater> ().isButtom)
			return;
		GameObject go = TPPool.Instance.GetWater ();
		go.transform.parent = waterRoot.transform;
		go.transform.localPosition = Vector3.zero;
		go.transform.localRotation = Quaternion.identity;
		go.transform.localScale = Vector3.one * 0.2f;
		go.GetComponent<Renderer> ().material.color = cutPanle_diguan.GetComponent<TestCutWater> ()._water.GetComponent<Renderer> ().material.color;
		go.GetComponent<WaterInfo> ().waterType = cutPanle_diguan.GetComponent<TestCutWater> ()._waterType;
		go.AddComponent<Rigidbody> ();
		cutPanle_diguan.GetComponent<TestCutWater> ().DownMine ();
		go.transform.parent = null;
	}

	public void AbsorbAction()
	{
		if (cutPanle_diguan.GetComponent<TestCutWater> ().isTop || absorbCutpanle.GetComponent<TestCutWater> ().isButtom)
			return;
		if (!cutPanle_diguan.GetComponent<TestCutWater> ().isButtom) {
			if (cutPanle_diguan.GetComponent<TestCutWater> ()._waterType != absorbCutpanle.GetComponent<TestCutWater> ()._waterType)
				return;
		} else {
			cutPanle_diguan.GetComponent<TestCutWater> ()._waterType = absorbCutpanle.GetComponent<TestCutWater> ()._waterType;
			cutPanle_diguan.GetComponent<TestCutWater> ()._water.GetComponent<Renderer> ().material.color = absorbCutpanle.GetComponent<TestCutWater> ()._water.GetComponent<Renderer>().material.color;
		}
		cutPanle_diguan.GetComponent<TestCutWater> ().RaiseMine ();
		absorbCutpanle.GetComponent<TestCutWater> ().DownMine ();
	}

	void OnDrawGizmos()
	{
		Gizmos.color = Color.red;
		Gizmos.DrawRay (waterRoot.transform.position, waterRoot.transform.forward);
	}
}
